package com.da.javatest.leetCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * @author chenlida
 * @date 2018/12/20 20:16
 * @description
 */
public class Code811 {
    public static void main(String[] args) {
        new Code811().subdomainVisits(new String[] {"9001 discuss.leetcode.com"});
    }

    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap<>();
        for (String cpdomain : cpdomains) {
            String[] s = cpdomain.split(" ");
            int num = Integer.parseInt(s[0]);
            addDomain(map, s[1], num);
        }
        List<String> result = map.entrySet().stream().map(x -> x.getValue() + " " + x.getKey()).collect(
            Collectors.toList());
        return result;
    }

    private void addDomain(Map<String, Integer> map, String s, int num) {
        if (map.containsKey(s)) {
            map.put(s, map.get(s) + num);
        } else {
            map.put(s, num);
        }
        if (s.contains(".")) {
            addDomain(map, s.substring(s.indexOf(".") + 1), num);
        }
    }
}
